package controller;

import java.util.ArrayList;

/**
 * @Title: NoticeController.java
 * @Description: TODO
 * @author 18130444郑雅玲
 * @date 2020-12-01 03:33:32
 */

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import service.NoticeService;
import po.Notice;

@Controller
@RequestMapping("/notice")
public class NoticeController {
	
	@Autowired
	private NoticeService noticeService;
	
	/**
	 * @Description: 查询所有公告
	 * @author 18130444郑雅玲
	 * @date 2020-12-01 00:40:36
	 */
	@RequestMapping("/select/{page}")
	public String select(Notice notice, Model model,@PathVariable int page) {
		
		page = (page -1) * 7;
		int totalPage = noticeService.pageCount();
		
		List<Notice> list = noticeService.findAllNotice(notice);
		List<Notice> list2 = noticeService.findNotices(page);
		ArrayList<Integer> curPage = new ArrayList<>();
		for(int i = 1; i <= totalPage; i ++) {
			curPage.add(i);
		}
		
		int totalData = list.size();
		model.addAttribute("noticeList", list2);
		model.addAttribute("curPage", curPage);
		model.addAttribute("totalData", totalData);
		model.addAttribute("totalPage",totalPage);
		return "noticeList";
	}
	
	/**
	 * @Description: 删除选定公告
	 * @author 18130444郑雅玲
	 * @date 2020-12-06 09:41:31
	 */
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable int id, Model model) {
//		System.out.println(id);
		int flag = noticeService.deteleNotice(id);
		if(flag == 0) {
			return "error";
		}
		return "forward:/notice/select/1";
	}
	
	/**
	 * @Description: 跳转添加公告页面
	 * @author 18130444郑雅玲
	 * @date 2020-12-08 00:43:00
	 */
	@RequestMapping("/toAdd")
	public String toAdd(Model model) {
		model.addAttribute("notice", new Notice());
		return "addNotice";
	}
	
	/**
	 * @Description: 添加公告
	 * @author 18130444郑雅玲
	 * @date 2020-12-09 00:43:49
	 */
	@RequestMapping("/add")
	public String add(@Valid @ModelAttribute Notice notice, BindingResult result, Model model) {
		if(result.hasErrors()) {
			return "addNotice";
		}
		noticeService.addNotice(notice);
		model.addAttribute("message", "公告添加成功！");
		return "addNotice";
	}
	
	/**
	 * @Description: 公告详情
	 * @author 18130444郑雅玲
	 * @date 2020-12-09 03:44:44
	 */
	@RequestMapping("/selectANotice")
	public String selectANotice(Model model, int id) {
		return noticeService.selectANotice(model, id);
	}
}